package com.zhazha.earlybird.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zhazha.earlybird.beans.UniversityInfo;

public class UniversityDAO {
	
	private SQLiteDatabase mDatabase;
	private static final String UNIVERSITY_TABLE = "university";
	
	private static final String UNIVERSITY_ID 				= "id";
	private static final String UNIVERSITY_NAME				= "name";
	private static final String UNIVERSITY_CITY_ID			= "city_id";
	
	private static final int UNIVERSITY_ID_INDEX 			= 0;
	private static final int UNIVERSITY_NAME_INDEX			= 1;
	private static final int UNIVERSITY_CITY_ID_INDEX		= 2;
	
	UniversityDAO(SQLiteDatabase db) {
		mDatabase = db;
	}
	
	
	public boolean insert(UniversityInfo university) {
		
		try {
			ContentValues cv = new ContentValues();
			cv.put(UNIVERSITY_ID, 	university.getId());
			cv.put(UNIVERSITY_NAME,   university.getName());
			cv.put(UNIVERSITY_CITY_ID, university.getCityId());
			
			this.mDatabase.insert(UNIVERSITY_TABLE, null, cv);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}
	
	public boolean delete(int id) {
		try {
			String whereClause = "id=?";
			String[] whereArgs = {String.valueOf(id)};
			this.mDatabase.delete(UNIVERSITY_TABLE, whereClause, whereArgs);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean update(int id, ContentValues cv) {
		try {
			String whereClause = "id=?";
			String[] whereArgs = {String.valueOf(id)};
			this.mDatabase.update(UNIVERSITY_TABLE, cv, whereClause, whereArgs);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public UniversityInfo queryById(int id) {
		UniversityInfo university = null;
		
		try {
			String selection = "id=?";
			String[] selectionArgs = {String.valueOf(id)};
			Cursor c = this.mDatabase.query(UNIVERSITY_TABLE, null, selection, selectionArgs, null, null, null);
			
			if(c.moveToFirst()) {
				university = new UniversityInfo();
				university.setId(c.getInt(UNIVERSITY_ID_INDEX));
				university.setName(c.getString(UNIVERSITY_NAME_INDEX));
				university.setCityId(c.getInt(UNIVERSITY_CITY_ID_INDEX));
			}
			
			return university;
			
		}catch (Exception e) {
			e.printStackTrace();
			return university;
		}
	}


}
